package com.qili.controller.supervisor;

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

/**
 * @author zhaoyongke
 * @date 2021/1/7
 * @description
 */
public class T {

   public static void main(String[] args) {
        try {



      /*      mergeWord("D:/tt/工程变更统计表_000_发布日期_工程名称.docx", "D:/tt/yz.doc");*/
            /*文字替换成书签*/
            String url="D:/tt/8.doc";
            String imageurl="D:\\tt\\101.jpg";
            String lebel="业主单位代表";
            String text="业主单位代表";
            insertLeble(url,text,lebel);
   /*         *//*书签替换成图片*//*
            HashMap<String,String> mapimg=new HashMap();
            mapimg.put(lebel,imageurl);
          replaceBookmarkWithImg(url,url,mapimg);*/

        } catch (Exception e) {

        }


    }

    public static void mergeWord(String targetWordPath, String copyWordPath) throws Exception {
        try {
            //targetWordPath文档
            Document targetword = new Document(targetWordPath);
            //copyWordPath插入到targetWordPath文档
            targetword.insertTextFromFile(copyWordPath, FileFormat.Docx_2013);
            //保存合并后的文档
            targetword.saveToFile(targetWordPath, FileFormat.Docx_2013);
            InputStream is = new FileInputStream(targetWordPath);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os = new FileOutputStream(targetWordPath);
            document.write(os);
            System.out.println("生成docx文档成功！");
            openWord(targetWordPath);

        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new Exception("合并文档出错：" + e.getMessage());
        }

    }

    public static void openWord(String filepath) {
        final Runtime runtime = Runtime.getRuntime();
        Process process = null;
        final String cmd = "rundll32 url.dll FileProtocolHandler file://" + filepath + "";//要打开的文件路径。
        try {
            process = runtime.exec(cmd);
        } catch (final Exception e) {
            System.out.println("Error exec!");
        }
    }

    public static void ss() {
        //实例化Document类的对象，并加载测试文档
        try {
            Document doc = new Document();
            doc.loadFromFile("D:\\tt\\2.doc");
            //加载替换的图片
            /*   Image image=Image.FromFile("g.png");*/
            Image image = ImageIO.read(new FileInputStream("D:\\tt\\101.jpg"));
            //获取第一个section
            Section sec = doc.getSections().get(0);
            //查找文档中的指定文本内容
            TextSelection[] selections = doc.findAllString("日期", true, true);
            int index = 0;
            TextRange range = null;
//遍历文档，移除文本内容，插入图片
            for (TextSelection selection : selections) {
                DocPicture pic = new DocPicture(doc);
                pic.loadImage(new FileInputStream("D:\\tt\\101.jpg"));
                pic.setWidth(50f);
                pic.setHeight(50f);
                range = selection.getAsOneRange();
                Paragraph para = range.getOwnerParagraph();
                index = para.getChildObjects().indexOf(range);
                //添加书签

                BookmarkStart start = new BookmarkStart(doc, "书签1");

                BookmarkEnd end = new BookmarkEnd(doc, "书签1");

                para.getChildObjects().insert(index, start);

                para.getChildObjects().insert(index + 2, end);


        /*        para.getChildObjects().insert(index,pic);
                para.getChildObjects().remove(range);*/
            }
            //保存文档
            doc.saveToFile("D:\\tt\\2.doc", FileFormat.Docx_2010);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //文字位置添加书签
    public  static  void insertLeble(String filePath,String text,String leble) {
        Document doc = new Document();
        try {
            doc.loadFromFile(filePath);
            //查找文档中的指定文本内容
            TextSelection[] selections = doc.findAllString(text, true, true);
            int index = 0;
            TextRange range = null;
            //遍历文档，移除文本内容，插入图片
            for (TextSelection selection : selections) {
                range = selection.getAsOneRange();
                Paragraph para = range.getOwnerParagraph();
                index = para.getChildObjects().indexOf(range);
                //添加书签
                BookmarkStart start = new BookmarkStart(doc, leble);
                BookmarkEnd end = new BookmarkEnd(doc, leble);
                para.getChildObjects().insert(index+2, start);
                para.getChildObjects().insert(index+3, end);
            }
            //获取第一个section
            Section section = doc.getSections().get(0);

            Table table = section.getTables().get(0);
          /*  table.applyStyle(DefaultTableStyle.Table_Grid);*/


            //给表格应用样式
      /*      table.applyStyle(DefaultTableStyle.);*/

            //设置表格的右边框
         /*   table.getTableFormat().getBorders().getRight().setBorderType(BorderStyle.Hairline);
            table.getTableFormat().getBorders().getRight().setLineWidth(1.0F);
            table.getTableFormat().getBorders().getRight().setColor(Color.RED);

            //设置表格的顶部边框
            table.getTableFormat().getBorders().getTop().setBorderType(BorderStyle.Hairline);
            table.getTableFormat().getBorders().getTop().setLineWidth(1.0F);
            table.getTableFormat().getBorders().getTop().setColor(Color.GREEN);

            //设置表格的左边框
            table.getTableFormat().getBorders().getLeft().setBorderType(BorderStyle.Hairline);
            table.getTableFormat().getBorders().getLeft().setLineWidth(1.0F);
            table.getTableFormat().getBorders().getLeft().setColor(Color.YELLOW);*/

            //设置表格的底部边框
            table.getTableFormat().getBorders().getTop().setBorderType(BorderStyle.Single);
            table.getTableFormat().getBorders().getBottom().setBorderType(BorderStyle.Single);

            //设置表格的水平和垂直边框
    /*        table.getTableFormat().getBorders().getVertical().setBorderType(BorderStyle.Dot);
            table.getTableFormat().getBorders().getHorizontal().setBorderType(BorderStyle.None);
            table.getTableFormat().getBorders().getVertical().setColor(Color.ORANGE);*/

            //保存文档
           doc.saveToFile(filePath);
            doc.dispose();

 /*           InputStream is = new FileInputStream(filePath);
            XWPFDocument document = new XWPFDocument(is);
            List<XWPFTable> tables=document.getTables();
            for (int i = 0; i <tables.size() ; i++) {
                XWPFTable table=  tables.get(i);*/
//                List<XWPFTableRow> rows=table.getRows();
//                for (int j = 0; j < rows.size(); j++) {
//                    XWPFTableRow  row= rows.get(j);
//                    row.
//                }

//                CTTblBorders borders = table.getCTTbl().getTblPr().getTblBorders();
//
//                CTBorder hBorder = borders.addNewInsideH();
//                hBorder.setVal(STBorder.Enum.forString("single"));  // 线条类型
//                hBorder.setSz(new BigInteger("1")); // 线条大小
//                hBorder.setColor("000000"); // 设置颜色
//
//                CTBorder vBorder = borders.addNewInsideV();
//                vBorder.setVal(STBorder.Enum.forString("single"));
//                vBorder.setSz(new BigInteger("10000000"));
//                vBorder.setColor("000000");
//
//                CTBorder lBorder = borders.addNewLeft();
//                lBorder.setVal(STBorder.Enum.forString("single"));
//                lBorder.setSz(new BigInteger("10000000"));
//                lBorder.setColor("000000");
//
//                CTBorder rBorder = borders.addNewRight();
//                rBorder.setVal(STBorder.Enum.forString("single"));
//                rBorder.setSz(new BigInteger("1"));
//                rBorder.setColor("000000");
//
//                CTBorder tBorder = borders.addNewTop();
//                tBorder.setVal(STBorder.Enum.forString("single"));
//                tBorder.setSz(new BigInteger("10000000"));
//                tBorder.setColor("000000");
//
//                CTBorder bBorder = borders.addNewBottom();
//                bBorder.setVal(STBorder.Enum.forString("single"));
//                bBorder.setSz(new BigInteger("10000000"));
//                bBorder.setColor("000000");
             /*   table.setInsideHBorder(XWPFTable.XWPFBorderType.SINGLE,100000,200000,"000000");
                table.setInsideVBorder(XWPFTable.XWPFBorderType.SINGLE,100000,200000,"000000");*/
                //table.createRow(); // 增加一行


           // }
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
    /*        document.removeBodyElement(0);*/

            //输出word内容文件流，新输出路径位置
           // OutputStream os = new FileOutputStream(filePath);
           // document.write(os);
        /*    doc.dispose();*/
            /*os.close();
            is.close();*/
           // os.close();
            System.out.println("文字位置添加书签成功");
        } catch (Exception e) {
          //  System.out.println("文字位置添加书签出错："+e.getMessage());
          //  e.printStackTrace();
        }finally {
 /*           doc.dispose();*/

        }

    }

    //文字替换标签
    public  static String ReplaceBookmarkContentWithNewContent(String filePath, String docUrl, Map<String, String> con) {
        //创建文档对象
        Document doc = new Document();
        //加载包含书签的Word文档
        doc.loadFromFile(docUrl);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = format.format(new Date());
        String docInfo = filePath + "/" + nowDate + ".docx";
        Iterator iter = con.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String lable = entry.getKey().toString();
            String content = entry.getValue().toString();
            //定位到指定书签位置
            BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc);
            bookmarksNavigator.moveToBookmark(lable);
            //用文本内容替换原有书签位置的文本，新替换的内容与原文格式一致
            bookmarksNavigator.replaceBookmarkContent(content, true);
        }
        //保存文档
        doc.saveToFile(filePath);

        doc.dispose();
        return docInfo;


    }

    //图片替换文档内标签
    public  static  void replaceBookmarkWithImg (String filePath, String docUrl, Map<String,String> con) {
        //加载包含书签的文档
        Document doc = new Document();
        InputStream is=null;
        OutputStream os=null;
        try {
            doc.loadFromFile(docUrl);
            Iterator iter = con.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String lable = entry.getKey().toString();
                String content = entry.getValue().toString();
                //定位到指定书签位置
                BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc);
                bookmarksNavigator.moveToBookmark(lable, true, true);
                //添加图片，替换原有书签内容
                Paragraph para = new Paragraph(doc);
                DocPicture pic2=para.appendPicture(content);
                pic2.setHeight(100f);
                pic2.setWidth(100f);
                TextBodyPart bodyPart = new TextBodyPart(doc);
                bodyPart.getBodyItems().add(para);
                bookmarksNavigator.replaceBookmarkContent(bodyPart);
            }
            //保存doc文档
            doc.saveToFile(filePath,FileFormat.Docx_2013);
            is = new FileInputStream(filePath);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            os = new FileOutputStream(filePath);
            document.write(os);
/*
            doc.saveToFile(filePath);*/
            doc.dispose();
            os.close();
            is.close();
            System.out.println("插入图片成功");
        } catch (Exception e) {
            System.out.println("插入图片出错："+e.getMessage());
            e.printStackTrace();
        } finally {
            doc.dispose();
        }
    }

/*  public static void main(String[] args) throws FileNotFoundException {
        String url="D:\\template\\doc\\工程变更单模板11.docx";
        List<String> list=new ArrayList<>();
        for (int i = 0; i <5 ; i++) {
            int y=i+1;
            list.add("PO_F"+y);
        }
          Map map= getTextByLebel(url,list);
         System.out.println(map);

    }*/

    public static  Map getTextByLebel(String  url, List<String> list){
        Map  map=new HashMap();
        Document doc = new Document();
        //加载Word文档
        doc.loadFromFile(url);
        for (int i = 0; i < list.size(); i++) {
            //获取指定书签
            BookmarksNavigator navigator = new BookmarksNavigator(doc);
            /*获取书签*/
            String lebel=list.get(i);
            navigator.moveToBookmark(lebel);
            //获取书签内容
            TextBodyPart textBodyPart = navigator.getBookmarkContent();
            //创建String变量
            String text = "";
            //遍历书签内容的项目
            for (Object item : textBodyPart.getBodyItems()) {
                //判断项目是否为段落
                if (item instanceof Paragraph) {
                    Paragraph paragraph = (Paragraph) item;
                    //遍历段落中的子对象
                    for (Object childObj : paragraph.getChildObjects()) {
                        //判断子对象是否为TextRange
                        if (childObj instanceof TextRange) {
                            //获取TextRange中的文本
                            TextRange textRange = (TextRange) childObj;
                            text = text + textRange.getText();
                        }
                    }
                }
            }
            //将获取到的文本写入Txt文件
            System.out.println(text);
            if("PO_F1".equals(lebel)){
                String textnew=text.replaceAll("由于","").replaceAll("原因","").replaceAll("_","");
                map.put("reason",textnew);
            }else if("PO_F2".equals(lebel)){
                String textnew=text.replaceAll("兹提出","").replaceAll("产品名称","").replaceAll("_","");
                map.put("name",textnew);
            }else if("PO_F3".equals(lebel)){
                String textnew=text.replaceAll("由","").replaceAll("变更","").replaceAll("_","");
                map.put("after",textnew);
            }else if("PO_F4".equals(lebel)){
                String textnew=text.replaceAll("为","").replaceAll("的工程变更","").replaceAll("_","");
                map.put("before",textnew);
            }else if("PO_F5".equals(lebel)){
                String textnew=text.replaceAll("变更金额为","").replaceAll("（内容见附件）","").replaceAll("_","");
                map.put("money",textnew);
            }
        }
        return  map;
    }
}








